/***************************************************************************
 *   Copyright (C) 2008 by Hector Francisco Hernandez                      *
 *   hectorfh@gmail.com                                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "car.h"
#include <string.h>
#include <stdlib.h>

#define NPATTERNS 3

char rpatterns[][MAX_CAR_LEN + 1] = { "(#0#)", "[####][]", "[]8))"};
char lpatterns[][MAX_CAR_LEN + 1] = { "(#0#)", "[][####]", "((8[]"};

struct car
{
  int x, y;
  int length;
  int color;
  int dir;
  chtype string[MAX_CAR_LEN + 1];
  WINDOW *window;
};

struct car *car_create(WINDOW *window, int x, int y, int dir)
{
  int i;
  int npattern;
  struct car *car = (struct car *) malloc(sizeof(struct car));

  car->x = x;
  car->y = y;
  car->color = (float) rand() / RAND_MAX * 2 + 1;
  car->dir = dir;

  npattern = (int) ((float) rand() / RAND_MAX * NPATTERNS);

  if (dir == 0) {
    for (i = 0; i < strlen(rpatterns[npattern]); i++) {
      car->string[i] = COLOR_PAIR(car->color) | rpatterns[npattern][i];
    }

    car->length = strlen(rpatterns[npattern]);
  }
  else {
    for (i = 0; i < strlen(lpatterns[npattern]); i++) {
      car->string[i] = COLOR_PAIR(car->color) | lpatterns[npattern][i];
    }

    car->length = strlen(lpatterns[npattern]);
  }

  car->window = window;

  return car;
}

void car_draw(struct car *car)
{
  int i, x;

  for (i = 0, x = car->x; i < car->length; i++, x++) {
    mvwaddch(car->window, car->y, x, car->string[i]);
  }
}

int car_isin(struct car *car, int x, int y)
{
  return y == car->y && x >= car->x && x <= car->x + car->length;
}

int car_length(struct car *car)
{
  return car->length;
}

void car_move(struct car *car)
{
  car->x += car->dir == 0 ? 1 : -1; 
}
